package com.example.controller;

import com.example.utils.IdWorker;
import com.example.utils.weixin.WeixinPayResult;
import com.example.utils.weixin.WeixinPayUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("/weixin")
public class WeixinPayController {
    @Value("${weixinPay.app_id}")
    private String appId;
    @Value("${weixinPay.mch_id}")
    private String mchId;
    @Value("${weixinPay.api_key}")
    private String apiKey;
    @GetMapping("/createNative")
    public WeixinPayResult createNative() {
        //自己系统生成的唯一的交易单号（yyyyMMdd+随机字符串（推特雪花算法生成19位数字）
//        String outTradeNo = "1234567891289343";
        String outTradeNo = getOnlyOrderNum();
        String body = "微信支付测试";
        WeixinPayResult weixinPayResult = WeixinPayUtils.createNative("http://www.baidu.com", appId, mchId, apiKey, outTradeNo, 1, body);
        System.out.println(weixinPayResult);
        return weixinPayResult;
    }

    @GetMapping("/queryPayStatus")
    public WeixinPayResult queryPayStatus(String outTradeNo) {
        return WeixinPayUtils.queryPayStatus(appId, mchId, apiKey, outTradeNo);
    }

    @GetMapping("/weixinRedPacket")
    public WeixinPayResult weixinRedPacket() {
        String mch_billno = "98765436543221";
        String re_openid = "o64up1KjlO-0Z3jp_UnceKdHpVeU";
        WeixinPayResult weixinPayResult = WeixinPayUtils.weixinRedPacket(appId, mch_billno, mchId, apiKey, re_openid, 100);
        return weixinPayResult;
    }

    @GetMapping("/bussinessPayToChange")
    public WeixinPayResult bussinessPayToChange() {
        String partner_trade_no = "123467834567";
        String openId = "o64up1KjlO-0Z3jp_UnceKdHpVeU";
        String checkName = "蔡文雯";
        WeixinPayResult weixinPayResult = WeixinPayUtils.bussinessPayToChange(appId, mchId, apiKey, partner_trade_no, openId, checkName, 100);
        return weixinPayResult;
    }

    /**
     * 是生成一个唯一的订单号
     *
     * @param
     * @return java.lang.String
     * @author caiwen
     * @date 2019-12-26
     */
    private String getOnlyOrderNum() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        IdWorker idWorker = new IdWorker(0, 0);
        return sdf.format(new Date()) + idWorker.nextId();
    }

}
